package org.ticlib.task
{
	import mx.rpc.AsyncToken;
	import mx.rpc.Responder;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;

	public class DelegateInvoker extends Task
	{
		public function DelegateInvoker()
		{
			super();
			responder = new Responder(onResult, onFault);
		}

		[Bindable] public var operation:Function;
		[Bindable] public var arguments:Object;
		
		/**
		 * function provide conversion to result
		 * if not specified then ResultEvent.result will use as result
		 * signature:
		 * 		function(rawData:Object):Object;
		 * */
		[Bindable] public var resultConverter:Function;
		
		private var responder:Responder;
		
		override public function stop():void
		{
			
		}
		
		override public function execute():void
		{
			initialize();
			var token:AsyncToken;
			if(this.arguments == null)
				token = operation.call(this);
			else
				token = operation.apply(this, this.arguments);
			token.addResponder(responder);
		}
		
		private function onResult(e:ResultEvent):void
		{
			if(resultConverter != null)
				resultObject = resultConverter.apply(this, [e.result]);
			else
				resultObject = e.result;
			isComplete = true;
			dispatchEvent(new Event(Event.COMPLETE));
			
			if(chain == null) return;
			if(parent == null){
				chain.execute();
				return;
			}
			if(!parent.isComplete)
				chain.execute();
		}
		
		private function onFault(e:FaultEvent):void
		{
			faultObject = e.fault;
			dispatchEvent(FaultEvent.createEvent(e.fault));
		}
		
		public function initialized(document:Object, id:String):void
		{
		}
	}
}